import { useRef, useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import { DownOutlined } from '@ant-design/icons';
import { Button, Dropdown, Menu, Modal, message, Form, Input, Select, DatePicker } from 'antd';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-components';
import {
  profileActivate,
  profileSearchWithPage,
  queryCount,
  profileToUat,
  profileExport,
} from '@/services/profile';
import type { ParamsType } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-table';
import type { PaginationProps, FormInstance } from 'antd';
import type { ActionType } from '@ant-design/pro-components';

import styles from './style.less';
import moment from 'moment';

const enumSelectFile = [
  // {
  //   label: '导出全部',
  //   value: 0,
  // },
  {
    label: '根据活动id导出',
    value: 1,
  },
  {
    label: '根据时间导出',
    value: 2,
  },
];

const { confirm } = Modal;

const ProfileList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<FormInstance>();

  const [modalFileForm] = Form.useForm();
  const [fileVisible, setFileVisible] = useState<boolean>(false);
  const [confirmLoad, setConfirmLoad] = useState<boolean>(false);
  const typeWatch = Form.useWatch('type', modalFileForm);

  // 跳转新增页
  const hanldleAdd = () => {
    history.push(`/profile/detail/add`);
  };

  // 跳编辑页
  const hanldleEdit = (record: any) => {
    history.push(`/profile/detail/modify/${record.activityId}`);
  };

  // 跳编辑页---复制
  const hanldleCopy = (record: any) => {
    history.push(`/profile/detail/add/${record.activityId}`);
  };

  // 提交&同步
  const handleSubmitSync = async (activityId: string) => {
    const [res1, res2] = await Promise.all([
      profileActivate({ activityIds: activityId }),
      profileToUat({ activityId: activityId }),
    ]);
    if (res1.code === 200 && res2.code === 200) {
      message.success('操作成功');
    }
    actionRef?.current?.reloadAndRest?.();
  };

  // 提交
  const handleOperate = (record: any, type: string) => {
    confirm({
      // title: '提醒',
      // icon: <ExclamationCircleOutlined style={{ color: '#3D50D6' }} />,
      content: `确认${type}活动：${record.activityId}？`,
      async onOk() {
        const params = {
          activityIds: record.activityId,
        };
        if (type === '提交&同步') {
          handleSubmitSync(record.activityId);
        }

        if (type === '提交') {
          try {
            const { code, data } = await profileActivate({ ...params });
            if (code === 200 && data) {
              message.success('操作成功');
              actionRef?.current?.reloadAndRest?.();
            }
          } catch (error) {}
        }
        if (type === '同步到PRE') {
          try {
            const { code, data } = await profileToUat({ activityId: record.activityId });
            if (code === 200 && data) {
              message.success('操作成功');
              actionRef?.current?.reloadAndRest?.();
            }
          } catch (error) {}
        }
      },
      onCancel() {},
    });
  };

  // 生成数量
  const handleQueryCount = async (activityId: string) => {
    const { code, data } = await queryCount({ activityId });
    if (code === 200 && data) {
      confirm({
        title: `当前生成数量:${data.hadGenCount}`,
        okCancel: false,
        okText: '我知道了',
        onOk() {},
      });
    }
  };

  // profileToUat

  const getItems = (record: API.ProfileListItem) => {
    return (
      <Menu>
        {/* <Menu.Item key="query">
          <a onClick={() => handleQueryCount(record.activityId)}>查询数量</a>
        </Menu.Item> */}
        {record.profileStatus === '填写中' && (
          <Menu.Item key="submit">
            {/* <a onClick={() => handleSubmitSync(record.activityId)}>提交&同步</a> */}
            <a onClick={() => handleOperate(record, '提交&同步')}>提交&同步</a>
          </Menu.Item>
        )}
        <Menu.Item key="sync">
          <a onClick={() => handleOperate(record, '同步到PRE')}>同步到PRE</a>
        </Menu.Item>
      </Menu>
    );
  };

  const columns: ProColumns<API.ProfileListItem>[] = [
    // 表单
    {
      title: '活动定义',
      dataIndex: 'activityId',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '宅急送优惠CODE',
      dataIndex: 'onlineCode',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动组批次',
      dataIndex: 'activityGroupRound',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '活动结束时间晚于',
      dataIndex: 'activityStartTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '活动结束时间晚于',
      },
    },

    {
      title: '活动结束时间早于',
      dataIndex: 'activityEndTime',
      valueType: 'date',
      hideInTable: true,
      fieldProps: {
        placeholder: '活动结束时间早于',
      },
    },

    {
      title: '劵名',
      dataIndex: 'activity',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },

    {
      title: '产品ID',
      dataIndex: 'productIdRule',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    {
      title: '后备产品码',
      dataIndex: 'productIdBackupEx',
      hideInTable: true,
      fieldProps: {
        placeholder: '请输入',
      },
    },
    // 表格
    {
      title: '活动定义',
      dataIndex: 'activityId',
      ellipsis: true,
      width: 200,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动组',
      dataIndex: 'activityGroup',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '给顾客开票支付ID',
      dataIndex: 'paymentIdA',
      ellipsis: true,
      width: 140,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '给第三方开票支付ID',
      dataIndex: 'paymentIdB',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动组批次',
      dataIndex: 'activityGroupRound',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券名',
      dataIndex: 'activity',
      ellipsis: true,
      width: 120,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放平台',
      dataIndex: 'placeChannelName',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放形式',
      dataIndex: 'placeStyle',
      ellipsis: true,
      width: 80,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券类型',
      dataIndex: 'couponTypeName',
      ellipsis: true,
      width: 60,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '宅急送优惠CODE',
      dataIndex: 'onlineCode',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '发放电子券数量',
      dataIndex: 'count',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '券净值',
      dataIndex: 'sales',
      ellipsis: true,
      width: 100,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动开始时间',
      dataIndex: 'activityStartTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '活动结束时间',
      dataIndex: 'activityEndTime',
      ellipsis: true,
      width: 150,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '主档状态',
      dataIndex: 'profileStatus',
      ellipsis: true,
      width: 90,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '使用规则类型',
      dataIndex: 'useRuleTypeName',
      ellipsis: true,
      width: 220,
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 200,
      align: 'center',
      hideInSearch: true,
      fixed: 'right',
      render(_, record) {
        return (
          <div key={record.id}>
            <a onClick={() => hanldleEdit(record)}>编辑</a>&nbsp;&nbsp;
            {record.profileStatus === '填写中' ? (
              <a onClick={() => handleOperate(record, '提交')}>提交</a>
            ) : (
              <span style={{ color: 'darkgray' }}>提交</span>
            )}
            &nbsp;&nbsp;
            <a onClick={() => hanldleCopy(record)}>复制</a>&nbsp;&nbsp;
            <Dropdown overlay={getItems(record)}>
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </div>
        );
      },
    },
  ];

  // 获取列表
  const getPromotionList = async (params: ParamsType) => {
    const { current, ...rest } = params;
    const param: API.ProfileSearchInfo = {
      pageNo: current || 1,
      pageSize: params.pageSize || 10,
      ...rest,
    };

    const { code, data } = await profileSearchWithPage(param);
    if (code === 200 && data) {
      const { rows, totalCount, pageSize, pageNo } = data;
      const arr: API.ProfileListItem[] = [];
      rows.forEach((item: any) => {
        arr.push({
          ...item.realProfileInfo,
        });
      });
      return {
        total: totalCount,
        pageSize,
        current: pageNo,
        data: arr,
      };
    }
    return {};
  };

  const showTotal: PaginationProps['showTotal'] = (t) => `共 ${t} 条`;

  const handleFileOK = async () => {
    modalFileForm.validateFields().then(async (values) => {
      // timeRange
      try {
        const { type, activityIds, timeRange } = values;
        const params: any = {};
        if (type === 1) {
          params.activityIds = activityIds;
        }
        if (type === 2) {
          if (!timeRange[1]) {
            message.error('请选择活动结束时间范围');
            return;
          }
          params.activityStartTime = timeRange[0]
            ? moment(timeRange[0]).format('YYYY-MM-DD HH:mm:ss')
            : '';
          params.activityEndTime = timeRange[1]
            ? moment(timeRange[1]).format('YYYY-MM-DD HH:mm:ss')
            : '';
        }

        setConfirmLoad(true);
        const resUpdate: any = await profileExport(params);
        setConfirmLoad(false);
        const url = window.URL.createObjectURL(resUpdate.data);
        const link = document.createElement('a');
        link.style.display = 'none';
        const Disposition = resUpdate?.Disposition || '';
        if (!Disposition) {
          message.error('暂无数据');
          return;
        }
        link.download =
          decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || '导出文件'; // 下载的文件名称
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success('导出成功');
        setFileVisible(false);
        modalFileForm.resetFields();
      } catch (error) {
        message.error('导出失败');
      }
    });
  };
  const handleFileCancel = () => {
    setConfirmLoad(false);
    setFileVisible(false);
    modalFileForm.resetFields();
  };

  return (
    <PageContainer>
      <div className={styles['form-body']}>
        <ProTable<API.ProfileListItem>
          rowKey="id"
          columns={columns}
          actionRef={actionRef}
          formRef={formRef}
          request={getPromotionList}
          options={false}
          search={{
            optionRender: (searchConfig, props, dom) => [...dom],
          }}
          toolBarRender={() => [
            <Button
              type="primary"
              key="out"
              onClick={() => {
                setFileVisible(true);
              }}
            >
              导出
            </Button>,
            <Button type="primary" key="add" onClick={() => hanldleAdd()}>
              新增
            </Button>,
          ]}
          scroll={{ x: 800 }}
          pagination={{
            showSizeChanger: true,
            size: 'small',
            showTotal,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
        />

        <Modal
          title="导出主档"
          width={620}
          open={fileVisible}
          onOk={handleFileOK}
          onCancel={handleFileCancel}
          confirmLoading={confirmLoad}
        >
          <Form
            labelCol={{ span: 6 }}
            form={modalFileForm}
            initialValues={{
              type: 1,
              activityIds: '',
              // activityStartTime: '',
              // activityEndTime: '',
              timeRange: [null, null],
            }}
          >
            <Form.Item label="导出条件" name="type">
              <Select options={enumSelectFile} />
            </Form.Item>

            {typeWatch === 1 && (
              <Form.Item
                label="活动id"
                name="activityIds"
                rules={[
                  {
                    required: true,
                    message: '不得为空',
                  },
                ]}
              >
                <Input.TextArea rows={4} placeholder="多个逗号隔开" />
              </Form.Item>
            )}
            {typeWatch === 2 && (
              <>
                <Form.Item
                  label="活动结束时间范围"
                  name="timeRange"
                  rules={[
                    {
                      required: true,
                      message: '不得为空',
                    },
                  ]}
                >
                  <DatePicker.RangePicker
                    style={{ width: '100%' }}
                    showTime
                    format={'YYYY-MM-DD HH:mm:ss'}
                  />
                </Form.Item>
                {/* <Form.Item label="活动结束时间晚于" name="activityStartTime">
                  <DatePicker style={{ width: '100%' }} showTime format={'YYYY-MM-DD HH:mm:ss'} />
                </Form.Item>
                <Form.Item label="活动结束时间早于" name="activityEndTime">
                  <DatePicker showTime style={{ width: '100%' }} format={'YYYY-MM-DD HH:mm:ss'} />
                </Form.Item> */}
              </>
            )}
          </Form>
        </Modal>
      </div>
    </PageContainer>
  );
};

export default ProfileList;
